package com.example.ticket.controller;

import com.example.ticket.bean.ResponseBean;
import com.example.ticket.entity.User;
import com.example.ticket.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Calendar;

@Controller
public class LoginController {
    @Autowired
    UserService userService;

    @GetMapping("/login")
    public  String toLoginPage(Model model){
        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        return "login";
    }

    @GetMapping("/checkCode")
    public String checkCode(String code){
        User user = userService.checkCode(code);
        System.out.println(user);
        //如果用户不等于null，把用户状态修改status=1
        if (user !=null){
            user.setStatus(1);
            //把code验证码清空，已经不需要了
            user.setCode("");
            userService.freezeById(user);
            System.out.println(user+"激活成功");
        }
        System.out.println("激活成功");
        return "login";
    }

    @GetMapping("/register")
    public String register(){return "register";}

    @GetMapping("/forgot")
    public String forgot(){return "forgot-password";}

    @GetMapping("/resetPassword")
    public String ResetPassword(String username, HttpSession session,Model model){
        model.addAttribute("username",username);
        session.setAttribute("Resetname",username);
        return "ResetPassword";
    }

    @ResponseBody
    @PostMapping("/ResetMyPassword")
    public ResponseBean ResetMyPassword(String password,HttpSession session){
        String Myusername=(String)session.getAttribute("Resetname");
        try{
        userService.ResetPassowrd(password,Myusername);
        return ResponseBean.success();
        }catch (Exception e){
            return ResponseBean.fail();
        }
    }


}
